package shweixin

import (
	"github.com/gin-gonic/gin"
	"log"
	"yundian/internel/app/dao"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/coupon"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
)

// HandleDrawDeviceCoupon 领取设备优惠券
func HandleDrawDeviceCoupon(ctx *gin.Context) {
	memberId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := make(request.DrawDeviceDiscountsReq)

	param["deviceSn"] = ""
	membersInfo := memberdao.NewMemberDao().GetMemberInfoById(memberId).Unwrap().(*membermodel.MembersModel)
	orderCouponInfo := dao.NewCouponDao().GetOrderCouponByName("反诈APP奖励优惠券").Unwrap().(*coupon.OrderCoupon)
	if membersInfo.ID == 0 || orderCouponInfo.Id == 0 {
		Response(ctx)("优惠发放失败", CodeInvalidParam, nil)(OK)
		return
	}

	if data := dao.NewDeviceDiscountsDao().GetDrawDeviceDiscountsRecordByUuid(membersInfo.UUID, "2"); data.ID > 0 {
		Response(ctx)("重复领取", CodeInvalidParam, false)(OK)
		return
	}

	paramCoupon := &request.GrantOrderCouponReq{MemberIds: []int{membersInfo.ID}, CouponId: orderCouponInfo.Id}
	if data := dao.NewCouponDao().GrantOrderCoupon(paramCoupon); data.Err != nil {
		Response(ctx)("", CodeInvalidParam, false)(OK)
		return
	}

	param["type"] = "2"
	param["uuid"] = membersInfo.UUID
	param["openId"] = membersInfo.WxOpenid
	if data := dao.NewDeviceDiscountsDao().DrawDeviceDiscountsRecord(param); data.Err != nil {
		Response(ctx)(data.Err.Error(), CodeInvalidParam, nil)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, true)(OK)
}

// HandleGetPlacesServiceMaterialsList 查询物品列表
func HandleGetPlacesServiceMaterialsList(c *gin.Context) {
	param := &request.WxPlacesServiceMaterialsListReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()

	data := dao.NewNotificationDaoDao().GetPlacesServiceMaterialsList(param)
	Response(c)("", CodeSuccess, data.Unwrap())(OK)
}

//服务通知
func HandleNotifications(c *gin.Context) {

	param := &placemodel.PlacesServiceNotification{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()

	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}

	//通知房间号不能为空
	if param.PlaceRoom == "" || param.PlaceId <= 0 {
		log.Println("服务通知房间号为空", param)
		Response(c)("", CodeError, nil)(OK)
		return
	}

	param.Status = 3
	param.MemberId = userId
	if notificationsInfo := logic.NewShWxNotificationsLogic().InitNotificationsData(param); notificationsInfo.Id <= 0 {
		Response(c)("", CodeError, nil)(OK)
	}
	Response(c)("通知成功", CodeSuccess, nil)(OK)
}
